package com.app.controller;

import com.app.bean.Movies;
import com.app.bean.News;
import com.app.bean.Ticket;
import com.app.core.ReturnVoCommon;
import com.app.service.NewsService;
import com.app.util.StringUtilsEx;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 师晓峰
 * @version V1.0
 * @date 2023/9/20 18:34
 * @Description: 用户相关的操作
 */
@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     * 新闻列表，带翻页功能
     *
     * @param title 新闻名称
     * @param page       当前第几页
     * @param rows       每页大小
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(String title, Integer page, Integer rows) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtilsEx.isEmpty(page)) {
            page = 1;
        }
        if (StringUtilsEx.isEmpty(rows)) {
            rows = 5;
        }
        // 分页
        PageHelper.startPage(page, rows);
        List<News> newsList = newsService.list(title);
        map.put("rows", newsList);
        PageInfo<News> pageInfo = new PageInfo<News>(newsList);
        map.put("total", pageInfo.getTotal());
        return map;
    }

    /**
     * 增加/修改一个新闻
     *
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ReturnVoCommon add(News news) {
        ReturnVoCommon vo = new ReturnVoCommon();
        try {
            if (StringUtilsEx.isEmpty(news.getId())){
                newsService.add(news);
            }else {
                newsService.update(news);
            }
        } catch (Exception e) {
            vo.setCode(-1);
            vo.setErrMsg("操作失败！");
        }
        vo.setCode(0);
        return vo;
    }

    /**
     * 删除一个新闻
     *
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ReturnVoCommon delete(String id) {
        ReturnVoCommon vo = new ReturnVoCommon();
        try {
            newsService.delete(id);
        } catch (Exception e) {
            vo.setCode(-1);
            vo.setErrMsg("删除失败！");
        }
        vo.setCode(0);
        return vo;
    }

    /**
     * 查找一个新闻
     *
     * @return
     */
    @RequestMapping("/getById")
    @ResponseBody
    public News getById(String id) {
        News news = newsService.getById(id);
        return news;
    }


}
